package com.drinkdelivery.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.drinkdelivery.common.constants.ProductConstant;
import com.drinkdelivery.common.domain.ProductBrand;
import com.drinkdelivery.common.domain.Products;
import com.drinkdelivery.common.exception.ServiceException;
import com.drinkdelivery.common.request.ProductCategoriesRequest;
import com.drinkdelivery.common.utils.file.FileUtils;
import com.drinkdelivery.mapper.ProductCategoriesMapper;
import com.drinkdelivery.service.IProductBrandService;
import com.drinkdelivery.service.IProductCategoriesService;
import com.drinkdelivery.service.IProductsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.drinkdelivery.common.domain.ProductCategories;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 商品分类Service业务层处理
 *
 * @author lzh
 * @date 2024-11-04
 */
@Service
public class ProductCategoriesServiceImpl extends ServiceImpl<ProductCategoriesMapper, ProductCategories> implements IProductCategoriesService
{
    @Autowired
    private ProductCategoriesMapper productCategoriesMapper;
    @Autowired
    private IProductBrandService productBrandService;

    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private IProductsService productsService;

    /**
     * 查询商品分类
     *
     * @param id 商品分类主键
     * @return 商品分类
     */
    @Override
    public ProductCategories selectProductCategoriesById(Long id)
    {
        //根据id获取未逻辑删除的数据
        LambdaQueryWrapper<ProductCategories> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(ProductCategories::getId,id)
                .eq(ProductCategories::getIsDeleted, 0);
        return this.getOne(lqw);
    }

    /**
     * 查询商品分类列表
     *
     * @param productCategories 商品分类
     * @return 商品分类
     */
    @Override
    public List<ProductCategories> selectProductCategoriesList(ProductCategories productCategories)
    {
        return productCategoriesMapper.selectProductCategoriesList(productCategories);
    }

    /**
     * 新增商品分类
     *
     * @param productCategories 商品分类
     * @return 结果
     */
    @Override
    public Boolean insertProductCategories(ProductCategories productCategories)
    {
        try {
        //参数检验
        validatorProductCategoriesParam(productCategories);
        //根据名称和patentId来查询该分类是否存在
        LambdaQueryWrapper<ProductCategories> lqw = new LambdaQueryWrapper<>();
        lqw.select(ProductCategories::getId);
        lqw.eq(ProductCategories::getIsDeleted, 0);
        lqw.eq(ProductCategories::getName, productCategories.getName());
        lqw.eq(ProductCategories::getParentId, productCategories.getParentId());
        lqw.last(" limit 1");
        if (ObjectUtil.isNotNull(productCategoriesMapper.selectOne(lqw))) {
            throw new ServiceException("该分类已存在");
        }

        //判断子级分类的level要大于1，且父parentId不能于0
        if (!productCategories.getLevel().equals(1)) {
            if (productCategories.getParentId().equals(0)) {
                throw new ServiceException("子级分类，父级ID不能为0");
            }

            //查询出父级分类，判断两个对象level等级大小
            ProductCategories productCategories1 = this.getById(productCategories.getParentId());
            if (productCategories.getLevel() >= productCategories1.getLevel())
                throw new ServiceException("新增的商品分类层级异常");
        }

            if (this.save(productCategories)){
                return true;
            }else {
                throw new RuntimeException();
            }

        } catch (RuntimeException e) {
            FileUtils.deleteFileIfExists(productCategories.getImageUrl());
            System.err.println("新增商品分类失败"+e);
            return false;
        }
    }

    /**
     * 修改商品分类
     *
     * @param request 商品分类
     * @return 结果
     */
    @Override
    public Boolean updateProductCategories(ProductCategoriesRequest request)
    {
        try {
            if (ObjectUtil.isNull(request.getId())) {
                throw new ServiceException("请选择分类，id为空");
            }
            ProductCategories productCategories = new ProductCategories();
            BeanUtils.copyProperties(request, productCategories);
            validatorProductCategoriesParam(productCategories);

            LambdaQueryWrapper<ProductCategories> lqw = new LambdaQueryWrapper<>();
            lqw.select(ProductCategories::getId);
            lqw.eq(ProductCategories::getIsDeleted, 0);
            lqw.eq(ProductCategories::getName, request.getName());
            if (ObjectUtil.isNotNull(request.getId()) && request.getId() > 0) {
                lqw.ne(ProductCategories::getId, request.getId());
            }
            lqw.last("limit 1");
            if (ObjectUtil.isNotNull(this.getOne(lqw)))
                throw new RuntimeException("该分类已存在");

//            BeanUtils.copyProperties(request, productCategories);
            if (updateById(productCategories)) {
                return true;
            } else {
                throw new RuntimeException();
            }
        } catch (RuntimeException e) {
            FileUtils.deleteFileIfExists(request.getImageUrl());
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 批量删除商品分类
     *
     * @param ids 需要删除的商品分类主键
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean deleteProductCategoriesByIds(Integer[] ids)
    {
        boolean flag = false;
        List<Integer> categoryIdList = Arrays.asList(ids);
        //判断该分类是否关联了商品
        //todo
        LambdaQueryWrapper<Products> productsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productsLambdaQueryWrapper.eq(Products::getCategoryId,categoryIdList);
        productsLambdaQueryWrapper.eq(Products::getIsDeleted,ProductConstant.NO_DELETE);
        List<Products> productsList = productsService.list(productsLambdaQueryWrapper);
        for (Products products:productsList){

        }
        //判断该分类是否关联了品牌
        LambdaQueryWrapper<ProductBrand> productBrandLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productBrandLambdaQueryWrapper.eq(ProductBrand::getCategoryId,categoryIdList);
        productBrandLambdaQueryWrapper.eq(ProductBrand::getIsDeleted,ProductConstant.NO_DELETE);
        List<ProductBrand> productBrandList = productBrandService.list(productBrandLambdaQueryWrapper);
        for (ProductBrand productBrand:productBrandList){
            ProductCategories productCategories = this.selectProductCategoriesById(productBrand.getCategoryId());
            throw new ServiceException(productCategories.getName()+"分类关联了"+productBrand.getBrandName());
        }

        //先删除一级分类
        LambdaUpdateWrapper<ProductCategories> luw = new LambdaUpdateWrapper<>();
        luw.in(ProductCategories::getId, Arrays.asList(ids));
        luw.set(ProductCategories::getIsDeleted, 1);
        this.update(luw);
        //根据父类parentId来删除二级分类
        luw.clear();
        luw.set(ProductCategories::getIsDeleted,1);
        luw.in(ProductCategories::getParentId,categoryIdList);
        flag = this.update(luw);

        //根据categoryIdList来查询出二级分类
        LambdaQueryWrapper<ProductCategories> lqw = new LambdaQueryWrapper<>();
        lqw.in(ProductCategories::getParentId,categoryIdList);
//        lqw.eq(ProductCategories::getIsDeleted,0);
        List<ProductCategories> productCategoriesList = this.list(lqw);
        //根据categoryIdList来查询出二级分类的id来作为parentId删除三级分类
        if(ObjectUtil.isNotNull(productCategoriesList)){
            List<Long> secondIdList = productCategoriesList.stream().map(ProductCategories::getId).collect(Collectors.toList());
            luw.clear();
            luw.set(ProductCategories::getIsDeleted,1);
            luw.in(ProductCategories::getParentId,secondIdList);
          flag = this.update(luw);
        }
        return flag;
    }

    /**
     * 删除商品分类信息
     *
     * @param id 商品分类主键
     * @return 结果
     */
    @Transactional
    @Override
    public Boolean deleteProductCategoriesById(Integer id)
    {
        LambdaUpdateWrapper<ProductCategories> luw = new LambdaUpdateWrapper<>();
        luw.eq(ProductCategories::getId,id);
        luw.set(ProductCategories::getIsDeleted,ProductConstant.DELETE);
        this.update(luw);

        luw.clear();
        luw.eq(ProductCategories::getParentId,id);
        luw.set(ProductCategories::getIsDeleted, ProductConstant.DELETE);

        LambdaQueryWrapper<ProductCategories> lqw = new LambdaQueryWrapper<>();
        lqw.select(ProductCategories::getId);
        lqw.eq(ProductCategories::getParentId,id);
//        lqw.eq(ProductCategories::getIsDeleted,ProductConstant.NO_DELETE);
        List<ProductCategories> productCategoriesList = this.list(lqw);
        if (ObjectUtil.isNotNull(productCategoriesList)){
            List<Long> idList = productCategoriesList.stream().map(ProductCategories::getId).collect(Collectors.toList());

            luw.clear();
            luw.in(ProductCategories::getParentId,idList);
            luw.set(ProductCategories::getIsDeleted,ProductConstant.DELETE);
            return this.update(luw);
        }
     return true;
    }


    public void validatorProductCategoriesParam(ProductCategories productCategories){
        if (ObjectUtil.isEmpty(productCategories.getName()))
            throw new RuntimeException("请填写分类名称");


        if (ObjectUtil.isEmpty(productCategories.getImageUrl()))
            throw new RuntimeException("请上传分类图片");

        if (ObjectUtil.isEmpty(productCategories.getSort()))
            throw new RuntimeException("请上传酒单排序");
    }
}
